<template>
	<view class="refund-request-page">
		<!-- 选择订单 -->
		<view class="form-section">
			<view class="section-header">
				<text class="section-title">选择订单</text>
				<text class="section-required">*</text>
			</view>
			<view class="order-select" @tap="showOrderPopup = true">
				<view class="picker-content">
					<view class="picker-left">
						<text class="picker-icon">📦</text>
						<text class="picker-text">{{ selectedOrder ? selectedOrder.displayText : '请选择要退款的订单' }}</text>
					</view>
					<text class="picker-arrow">›</text>
				</view>
			</view>
		</view>
		<!-- 自定义订单选择弹窗 -->
		<view class="order-popup" v-if="showOrderPopup">
			<view class="order-popup-container">
				<view class="order-popup-header">
					<text>选择要退款的订单</text>
					<text class="close-btn" @tap="showOrderPopup = false">×</text>
				</view>
				<view class="order-popup-list">
					<template v-if="orderList.length > 0">
						<view
							v-for="(order, idx) in orderList"
							:key="order.order_id"
							class="order-popup-item"
							@tap="selectOrder(order)"
						>
							<view class="order-popup-row">
								<text class="order-type">{{ getOrderTypeText(order.orderType) }}</text>
								<text class="order-no">{{ order.orderId }}</text>
							</view>
							<view class="order-popup-row">
								<text>金额：¥{{ order.payableAmount }}</text>
								<text>下单：{{ order.placeOrderTime }}</text>
							</view>
							<view class="order-popup-row" v-if="order.remark">
								<text>备注：{{ order.remark }}</text>
							</view>
						</view>
					</template>
					<template v-else>
						<view class="order-empty-tip">
							<text>暂无可退款订单</text>
						</view>
					</template>
				</view>
			</view>
		</view>

		<!-- 订单信息 -->
		<view v-if="selectedOrder" class="form-section">
			<view class="section-header">
				<text class="section-title">订单信息</text>
			</view>
			<view class="order-info-card">
				<view class="info-row">
					<text class="info-label">订单号</text>
					<text class="info-value">{{ selectedOrder.orderId }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">订单金额</text>
					<text class="info-value amount">¥{{ selectedOrder.payableAmount }}</text>
				</view>
				<view class="info-row">
					<text class="info-label">下单时间</text>
					<text class="info-value">{{ formatDate(selectedOrder.placeOrderTime) }}</text>
				</view>
			</view>
		</view>

		<!-- 退款原因 -->
		<view class="form-section">
			<view class="section-header">
				<text class="section-title">退款原因</text>
				<text class="section-required">*</text>
			</view>
			<view class="reason-grid">
				<view 
					v-for="(reason, index) in refundReasons" 
					:key="index"
					class="reason-item"
					:class="{ active: selectedReason === reason }"
					@tap="selectReason(reason)"
				>
					<text class="reason-text">{{ reason }}</text>
					<view v-if="selectedReason === reason" class="reason-check">✓</view>
				</view>
			</view>
		</view>

		<!-- 退款说明 -->
		<view class="form-section">
			<view class="section-header">
				<text class="section-title">退款说明</text>
				<text class="section-optional">（选填）</text>
			</view>
			<view class="textarea-container">
				<textarea 
					class="refund-desc"
					v-model="refundDesc"
					placeholder="请详细描述退款原因，帮助我们更好地处理您的申请..."
					maxlength="200"
				/>
				<text class="word-count">{{ refundDesc.length }}/200</text>
			</view>
		</view>

		<!-- 上传凭证 -->
		<view class="form-section">
			<view class="section-header">
				<text class="section-title">上传凭证</text>
				<text class="section-optional">（选填）</text>
			</view>
			<view class="upload-section">
				<view class="image-grid">
					<view 
						v-for="(image, index) in images" 
						:key="image.sortOrder"
						class="image-item-wrap"
					>
						<view class="image-item">
							<image :src="image.imagePath" mode="aspectFill" />
							<view class="sort-btns">
								<button v-if="index > 0" class="sort-btn up" @tap="moveImageUp(index)"><text class="sort-arrow">↑</text></button>
								<button v-if="index < images.length-1" class="sort-btn down" @tap="moveImageDown(index)"><text class="sort-arrow">↓</text></button>
							</view>
						</view>
						<view class="delete-btn-x-outside" @tap="deleteImage(index)"><text class="delete-x">×</text></view>
					</view>
					<view 
						class="upload-btn"
						@tap="chooseImage"
						v-if="images.length < 3"
					>
						<text class="upload-icon">📷</text>
						<text class="upload-text">上传图片</text>
					</view>
				</view>
				<text class="upload-tip">点击图片右上角按钮可排序，最多上传3张图片，支持jpg、png格式</text>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<button 
				class="submit-btn"
				:class="{ disabled: !selectedReason || !selectedOrder }"
				:disabled="!selectedReason || !selectedOrder"
				@tap="submitRefund"
			>
				<text class="submit-text">提交申请</text>
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { orderApi, refundApi } from '../../api'

const showOrderPopup = ref(false)

// 订单类型映射
function getOrderTypeText(type) {
	return type === 1 ? '堂食' : '外卖'
}

// 可退款的订单列表（测试数据，实际应从接口获取）
const orderList = ref([])

// 选中的订单
const selectedOrder = ref(null)

// 退款原因列表
const refundReasons = [
	'商品质量问题',
	'商品与描述不符',
	'配送时间过长',
	'重复下单',
	'其他原因'
]

// 选中的退款原因
const selectedReason = ref('')

// 退款说明
const refundDesc = ref('')

// 图片对象数组，包含 image_path 和 sort_order
const images = ref([])

// 退款申请
const refundRequest = ref({})

// 选择订单
const selectOrder = (order) => {
	selectedOrder.value = order
	showOrderPopup.value = false
}

// 选择退款原因
const selectReason = (reason) => {
	selectedReason.value = reason
}

// 选择图片
const chooseImage = () => {
	uni.chooseImage({
		count: 3 - images.value.length,
		success: (res) => {
			const startOrder = images.value.length + 1
			const newImages = res.tempFilePaths.map((path, idx) => ({
				imagePath: path,
				sortOrder: startOrder + idx
			}))
			images.value = [...images.value, ...newImages]
		}
	})
}

// 删除图片并重排
const deleteImage = (index) => {
	images.value.splice(index, 1)
	images.value.forEach((img, idx) => img.sortOrder = idx + 1)
	console.log(images.value)
}

// 移除拖拽相关逻辑，恢复按钮排序
const moveImageUp = (index) => {
	if (index === 0) return
	const arr = [...images.value]
	const temp = arr[index]
	arr[index] = arr[index - 1]
	arr[index - 1] = temp
	arr.forEach((img, idx) => img.sortOrder = idx + 1)
	images.value = arr
}
const moveImageDown = (index) => {
	if (index === images.value.length - 1) return
	const arr = [...images.value]
	const temp = arr[index]
	arr[index] = arr[index + 1]
	arr[index + 1] = temp
	arr.forEach((img, idx) => img.sortOrder = idx + 1)
	images.value = arr
}

// 格式化日期
const formatDate = (date) => {
	if (!date) return ''
	// 兼容iOS：将"2024-03-15 13:45:00"转为"2024/03/15 13:45:00"
	let d = date
	if (typeof d === 'string') {
		d = d.replace(/-/g, '/').replace('T', ' ').replace(/\.\d+/, '')
	}
	const dt = new Date(d)
	if (isNaN(dt.getTime())) return date // fallback
	return `${dt.getFullYear()}-${String(dt.getMonth() + 1).padStart(2, '0')}-${String(dt.getDate()).padStart(2, '0')} ${String(dt.getHours()).padStart(2, '0')}:${String(dt.getMinutes()).padStart(2, '0')}`
}

// 提交退款申请
const submitRefund = async () => {
	if (!selectedReason.value || !selectedOrder.value) {
		uni.showToast({
			title: '请选择订单和退款原因',
			icon: 'none'
		})
		return
	}

	try {
		// 这里添加提交退款申请的接口调用
		uni.showLoading({
			title: '提交中...'
		})
		const token = uni.getStorageSync('token')
		refundRequest.value = {
			orderId: selectedOrder.value.orderId,
			reason: selectedReason.value,
			requestAmount: selectedOrder.value.payableAmount,
			uId: token,
			refundDesc: refundDesc.value,
		}
		const res = await refundApi.submitRefund(refundRequest.value)
		console.log(res)
		if(images.value.length === 0){
			uni.hideLoading()
			uni.showToast({
				title: '申请提交成功',
				icon: 'success'
			})

			// 返回上一页
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
			return
		}
		
		const uploadTasks = Object.entries(images.value).map(([key, file],index) => {

			console.log("index:"+index)
			if(index != 0){
				refundRequest.value = null
			}
			
			const refundImage = {
				rrId: res.data,
				imagePath: file.imagePath,
				sortOrder: file.sortOrder
			}
			console.log("refundImage:"+refundImage)
			return new Promise((resolve, reject) => {
				if(!file || !file.imagePath){
					reject(new Error(`文件 ${key} 不存在`));
					return;
				}
				uni.uploadFile({
					url: 'http://192.168.29.125:8080/api/refundDTO/submit',
					filePath: file.imagePath,
					name: 'file',
					header: {
						'auth': token
					},
					formData: {
						refundImage : JSON.stringify(refundImage)
					},
					success: (uploadRes) => {
						try {
							const data = JSON.parse(uploadRes.data);
							if (data.code === 200) {
								resolve(data);
							} else {
								reject(new Error(data.message || '上传失败'));
							}
						} catch (parseError) {
							reject(new Error('服务器响应格式错误'));
						}
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		})

		//等待所有图片上传成功
		await Promise.all(uploadTasks);

		uni.hideLoading()
		uni.showToast({
			title: '申请提交成功',
			icon: 'success'
		})

		// 返回上一页
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	} catch (error) {
		uni.hideLoading()
		uni.showToast({
			title: '提交失败，请重试',
			icon: 'none'
		})
	}
}

// 预留：获取可退款的订单列表接口
const getOrderList = async () => {
	try {
		const uId = uni.getStorageSync('token')
		console.log(uId)
		const res = await orderApi.listRefundOrders(uId)
		orderList.value = res.data
		orderList.value.forEach(item => {
			item.displayText = `${getOrderTypeText(item.orderType)} | ${item.orderId} | ¥${item.payableAmount} | ${item.placeOrderTime}`
		})
		console.log(orderList.value)
	} catch (error) {
		console.error('获取订单列表失败：', error)
	}
}

onMounted(() => {
	getOrderList()
})
</script>

<style lang="scss" scoped>
.refund-request-page {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 24rpx;
}

.form-section {
	margin-bottom: 48rpx;
	background: #fff;
	border-radius: 20rpx;
	padding: 32rpx;
	box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #333;
		}

		.section-required {
			color: #ff4757;
			font-size: 32rpx;
			margin-left: 8rpx;
		}

		.section-optional {
			color: #999;
			font-size: 26rpx;
			margin-left: 8rpx;
		}
	}
}

.order-select {
	.picker-content {
		background: #f8f9fa;
		padding: 32rpx;
		border-radius: 16rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border: 2rpx solid #e9ecef;
		transition: all 0.3s ease;

		&:active {
			background: #e9ecef;
			border-color: #dee2e6;
		}

		.picker-left {
			display: flex;
			align-items: center;
			gap: 16rpx;

			.picker-icon {
				font-size: 40rpx;
				color: #6c757d;
			}

			.picker-text {
				font-size: 30rpx;
				color: #333;
				font-weight: 500;
			}
		}

		.picker-arrow {
			color: #adb5bd;
			font-size: 32rpx;
			font-weight: 300;
		}
	}
}

.order-info-card {
	background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
	padding: 32rpx;
	border-radius: 16rpx;
	border: 2rpx solid #dee2e6;

	.info-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;

		&:last-child {
			margin-bottom: 0;
		}

		.info-label {
			font-size: 28rpx;
			color: #6c757d;
			font-weight: 500;
		}

		.info-value {
			font-size: 30rpx;
			color: #333;
			font-weight: 600;

			&.amount {
				color: #ff6b6b;
				font-weight: 700;
			}
		}
	}
}

.reason-grid {
	display: grid;
	grid-template-columns: repeat(2, 1fr);
	gap: 20rpx;

	.reason-item {
		padding: 24rpx;
		background: #f8f9fa;
		border-radius: 16rpx;
		font-size: 28rpx;
		color: #495057;
		transition: all 0.3s ease;
		border: 2rpx solid transparent;
		position: relative;
		text-align: center;

		&.active {
			background: linear-gradient(135deg, #1b3c4b 0%, #2e5c6a 100%);
			color: #fff;
			border-color: #1b3c4b;
			transform: translateY(-2rpx);
			box-shadow: 0 8rpx 25rpx rgba(27, 60, 75, 0.3);

			.reason-check {
				display: flex;
			}
		}

		.reason-text {
			font-weight: 500;
		}

		.reason-check {
			position: absolute;
			top: 8rpx;
			right: 8rpx;
			width: 32rpx;
			height: 32rpx;
			background: rgba(255, 255, 255, 0.2);
			border-radius: 50%;
			display: none;
			align-items: center;
			justify-content: center;
			font-size: 20rpx;
			color: #fff;
		}
	}
}

.textarea-container {
	position: relative;

	.refund-desc {
		width: 100%;
		height: 240rpx;
		background: #f8f9fa;
		border-radius: 16rpx;
		padding: 32rpx;
		font-size: 28rpx;
		color: #333;
		border: 2rpx solid #e9ecef;
		transition: all 0.3s ease;

		&:focus {
			border-color: #1b3c4b;
			background: #fff;
		}
	}

	.word-count {
		position: absolute;
		bottom: 16rpx;
		right: 16rpx;
		font-size: 24rpx;
		color: #adb5bd;
		background: rgba(255, 255, 255, 0.8);
		padding: 4rpx 12rpx;
		border-radius: 12rpx;
	}
}

.upload-section {
	.image-grid {
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx;
		margin-bottom: 16rpx;
	}

	.image-item-wrap {
		position: relative;
		display: inline-block;
	}

	.image-item {
		position: relative;
		width: 100%;
		height: 200rpx;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);

		image {
			width: 100%;
			height: 100%;
		}
	}

	.delete-btn-x-outside {
		position: absolute;
		top: -16rpx;
		right: -16rpx;
		width: 40rpx;
		height: 40rpx;
		background: rgba(255,255,255,0.85);
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 4;
		box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.10);
		transition: background 0.2s;
	}

	.delete-btn-x-outside:active {
		background: #ff4757;
	}

	.delete-x {
		font-size: 32rpx;
		color: #222;
		font-weight: bold;
		line-height: 1;
	}

	.delete-btn-x-outside:active .delete-x {
		color: #fff;
	}

	.upload-btn {
		width: 100%;
		height: 200rpx;
		background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
		border-radius: 16rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border: 2rpx dashed #dee2e6;
		transition: all 0.3s ease;

		&:active {
			background: #e9ecef;
			border-color: #adb5bd;
		}

		.upload-icon {
			font-size: 48rpx;
			color: #6c757d;
			margin-bottom: 12rpx;
		}

		.upload-text {
			font-size: 26rpx;
			color: #6c757d;
			font-weight: 500;
		}
	}

	.upload-tip {
		font-size: 24rpx;
		color: #adb5bd;
		text-align: center;
	}
}

.sort-btns {
	position: absolute;
	top: 64rpx;
	right: 8rpx;
	display: flex;
	flex-direction: column;
	gap: 8rpx;
	z-index: 2;
}
.sort-btn {
	width: 44rpx;
	height: 44rpx;
	border-radius: 50%;
	background: linear-gradient(135deg, #1b3c4b 0%, #2e5c6a 100%);
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
	padding: 0;
	margin: 0;
	box-shadow: 0 2rpx 8rpx rgba(27, 60, 75, 0.12);
	transition: background 0.2s;
}
.sort-btn:active {
	background: #2e5c6a;
}
.sort-arrow {
	font-size: 30rpx;
	color: #fff;
	font-weight: bold;
	line-height: 1;
}

.submit-section {
	margin-top: 80rpx;
	padding-top: 32rpx;
	border-top: 2rpx solid #f0f0f0;

	.submit-btn {
		width: 100%;
		height: 96rpx;
		font-size: 32rpx;
		border-radius: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: linear-gradient(135deg, #1b3c4b 0%, #2e5c6a 100%);
		color: #fff;
		font-weight: 600;
		box-shadow: 0 8rpx 25rpx rgba(27, 60, 75, 0.3);
		transition: all 0.3s ease;

		&:active {
			transform: translateY(2rpx);
			box-shadow: 0 4rpx 15rpx rgba(27, 60, 75, 0.3);
		}

		&.disabled {
			background: linear-gradient(135deg, #dee2e6 0%, #adb5bd 100%);
			box-shadow: none;
			color: #6c757d;

			&:active {
				transform: none;
			}
		}

		.submit-text {
			font-weight: 600;
		}
	}
}

.order-popup {
	position: fixed;
	left: 0;
	top: 0;
	width: 100vw;
	height: 100vh;
	background: rgba(0,0,0,0.25);
	z-index: 1000;
	display: flex;
	align-items: flex-end;
	justify-content: center;
}
.order-popup-container {
	width: 100vw;
	background: #fff;
	border-top-left-radius: 24rpx;
	border-top-right-radius: 24rpx;
	padding-bottom: env(safe-area-inset-bottom);
	max-height: 70vh;
	overflow-y: auto;
	box-shadow: 0 -4rpx 24rpx rgba(27, 60, 75, 0.10);
	animation: popupIn 0.2s;
}
@keyframes popupIn {
	from { transform: translateY(100%); }
	to { transform: translateY(0); }
}
.order-popup-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 32rpx 32rpx 0 32rpx;
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}
.close-btn {
	font-size: 40rpx;
	color: #999;
	font-weight: bold;
	padding: 0 8rpx;
	cursor: pointer;
}
.order-popup-list {
	max-height: 50vh;
	overflow-y: auto;
	padding: 24rpx 0 32rpx 0;
}
.order-empty-tip {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 200rpx;
	color: #adb5bd;
	font-size: 30rpx;
}
.order-popup-item {
	background: #f8f9fa;
	margin: 0 24rpx 24rpx 24rpx;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(27, 60, 75, 0.06);
	padding: 24rpx;
	transition: background 0.2s;
}
.order-popup-item:active {
	background: #e9ecef;
}
.order-popup-row {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12rpx;
	font-size: 28rpx;
	color: #333;
}
.order-type {
	color: #1b3c4b;
	font-weight: bold;
}
.order-no {
	color: #999;
	font-size: 24rpx;
}
</style>
